package com.though.oos.soa;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import com.though.oos.config.OssConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.though.oos.config.OssConfig;

public class OssManager {

	private static Logger logger = LoggerFactory.getLogger(OssManager.class);

	public static OssConfig config = new OssConfig();

	public static String default_bucket_name = "caichen";
	
	public static String request_url = "http://%s.oss-cn-shenzhen.aliyuncs.com/";
	
	
	public static OSSClient client = new OSSClient(config.getConfigParams().getEndpoint(), config.getConfigParams().getAccessKey(),
			config.getConfigParams().getAccessKeySecret());
	

	/**
	 * 新建Bucket
	 */
	public static boolean createBucket(String bucketName) {
		if (StringUtils.isBlank(bucketName)) return false;
		
		if (client.doesBucketExist(bucketName)) return true;
		
		Bucket bucket = client.createBucket(bucketName);
		return bucketName.equals(bucket.getName());
	}

	
	/**
	 * 删除Bucket
	 */
	public static void deleteBucket(String bucketName) {
		if (StringUtils.isBlank(bucketName)) return;
		
		client.deleteBucket(bucketName);
		logger.info("删除oss bucket:{} 成功！", bucketName);
	}
	
	
	/**
	 * 向阿里云的OSS存储中存储文件  bucketName+path
	 */
	public static String uploadFile(InputStream in, String bucketName, FileTypeEnum fileType) {
		if (fileType == null) return null;
		String pathFile = processPathFile(fileType);
		if (StringUtils.isBlank(pathFile)) return null;
		
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setCacheControl("no-cache");
		metadata.setHeader("Pragma", "no-cache");
		metadata.setContentEncoding("utf-8");
		try {
			metadata.setContentLength(in.available());
			PutObjectResult putResult = client.putObject(StringUtils.isBlank(bucketName) ? default_bucket_name : bucketName, 
					pathFile, in, metadata);
			// 访问路径
			if (putResult != null && StringUtils.isNotBlank(putResult.getETag())) 
				return String.format(request_url, StringUtils.isBlank(bucketName) ? default_bucket_name : bucketName) + pathFile;
			return null;
		} catch (Exception e) {
			logger.error("Error oss updateFile exception", e);
			throw new RuntimeException("图片上传到oss失败！", e);
		}
	}

	
	/**
	 * 删除oss文件
	 * @param pathFile  文件的相对路径
	 */
	public static boolean deleteFile(String bucketName, String pathFile) {
		try {
			client.deleteObject(StringUtils.isBlank(bucketName) ? default_bucket_name : bucketName, pathFile);
		} catch (Exception e) {
			logger.error("Error oss deleteFile exception", e);
			return false;
		}
		return true;
	}
	
	
	
	/**
	 * 获取文件相对路径及名称
	 */
	private static String processPathFile(FileTypeEnum fileType) {
		Random random = new Random();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		if (fileType == FileTypeEnum.JPG) {
			return "image/" + format.format(new Date()) + "/" + String.valueOf(System.currentTimeMillis()) + String.valueOf(random.nextInt(1000)) + ".jpg";
		} else if (fileType == FileTypeEnum.PNG) {
			return "image/" + format.format(new Date()) + "/" + String.valueOf(System.currentTimeMillis()) + String.valueOf(random.nextInt(1000)) + ".png";
		} else if (fileType == FileTypeEnum.MP4) {
			return "video/" + format.format(new Date()) + "/" + String.valueOf(System.currentTimeMillis()) + String.valueOf(random.nextInt(1000)) + ".mp4";
		} else if (fileType == FileTypeEnum.FLV) {
			return "flv/" + format.format(new Date()) + "/" + String.valueOf(System.currentTimeMillis()) + String.valueOf(random.nextInt(1000)) + ".flv";
		}
		return "";
	}


	
	/*public static void main(String[] strs) throws FileNotFoundException {
		File file = new File("D:/aaa.png");
		InputStream in = new FileInputStream(file);
		
		System.out.println(uploadFile(in, null, FileTypeEnum.PNG));
		// image/20170827/1503814605588466.png
		System.out.println(deleteFile(null, "image/20170827/201700000000.png"));
	}*/
}
